<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Http;
use think\Controller;
use think\Db;
use weixin\TemplateMsg;

class Index extends Controller
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        return $this->view->fetch();
    }

    public function sendReport($id = 0)
    {
        $temp_msg = new TemplateMsg();
        $res = $temp_msg->reportMsg($id);
        if ($res !== false) {
            return 'success';
        } else {
            return 'fail';
        }
    }


    public function bindWechat()
    {

        return $this->view->fetch();
    }

    public function doBind()
    {

        $openid = session('wx_openid');
        if (empty($openid)) {
            $this->error('未获取到微信授权信息');
        }

        $mobile = $this->request->param('mobile');
        $reg_phone = '/^1[34578]\d{9}$/';
        if (empty($mobile) || !preg_match($reg_phone, $mobile)) {
            $this->error('手机号错误');
        }

        /*$user = Db::name('user')->where('mobile', $mobile)->find();
        if (empty($user)) {
            $this->error('没有查到用户信息，请稍后再试');
        }*/
        $check = Db::name('shopro_user_oauth')
            ->where([
                'provider' => 'wechat',
                'platform' => 'wxOfficialAccount',
                'openid' => $openid,
            ])
            ->find();
        if ($check) {
            $this->error('已绑定过了');
        }

        $res = Db::name('shopro_user_oauth')
            ->insert([
                'user_id' => 0,
                'mobile' => $mobile,
                'provider' => 'wechat',
                'platform' => 'wxOfficialAccount',
                'openid' => $openid,
            ]);

        if ($res) {
            $this->success('绑定成功');
        } else {
            $this->error('绑定失败');
        }


    }

    public function lists()
    {
        $openid = session('wx_openid');

        if (empty($openid)) {
            session('jump_url', url('lists'));
            $this->wxLogin();
        }
        return $this->view->fetch();
    }

    public function getLists()
    {
        $openid = session('wx_openid');

        $kw = $this->request->param('kw', '', 'trim');
        $mobile = Db::name('shopro_user_oauth')
            ->where([
                'provider' => 'wechat',
                'platform' => 'wxOfficialAccount',
                'openid' => $openid,
            ])
            ->value('mobile', 0);

        $where['mobile'] = $mobile;
        if ($kw) {
            $where['title'] = ['like', "%$kw%"];
        }
        $list = Db::name('shopro_report')
            ->where($where)
            ->field('id,title,test_date,pdf')
            ->order('id', 'desc')
            ->paginate(20);

        $data = $list->toArray();
        $result = array_merge([
            'code' => 1,
            'msg' => '成功'
        ], $data);
        return json($result);
    }

    public function wxLogin()
    {
        //微信登录
        $wx_appid = config('wx.appId');
        $wx_appsecret = config('wx.appSecret');
        $redirect_url = url('index/wxlogin', '', '', true);
        $from = input('from', 'wx');


        if (!isset($_GET['code'])) {
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wx_appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_userinfo&state={$from}#wechat_redirect";//snsapi_userinfo
            $this->redirect($url);
        }

        $code = input('code');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$wx_appid}&secret={$wx_appsecret}&code={$code}&grant_type=authorization_code";
        $wx_res = Http::get($url);
        trace('wx_res:' . $wx_res, 'debug');
        $res = json_decode($wx_res);

        if (isset($res->errcode)) {
            $this->error($res->errmsg);
        }
        $openid = $res->openid;
        $access_token = $res->access_token;
        $refresh_token = $res->refresh_token;

        $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $user_info = Http::get($url2);
        trace('$user_info:' . $user_info, 'debug');
        $user_info = json_decode($user_info, true);
        $openid = $user_info['openid'];
        session('wx_openid', $openid);

        $j_url = session('jump_rul');
        if (empty($j_url)) {

            $check = Db::name('shopro_user_oauth')
                ->where([
                    'provider' => 'wechat',
                    'platform' => 'wxOfficialAccount',
                    'openid' => $openid,
                ])
                ->find();
            if ($check) {
                $j_url = url('lists');
            } else {
                $j_url = url('bindWechat');
            }

        }
        $this->redirect($j_url);

    }

    public function test()
    {
        session('wx_openid',null);
        cache('jsapi_access_token', null);
        $temp_msg = new TemplateMsg();
        $res = $temp_msg->reportMsg(1);
        var_dump($res);
    }

    public function a()
    {
        $this->error('测试a');
    }

}
